package com.qg.lizhanqi.videosquare.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.qg.lizhanqi.videosquare.R;
import com.qg.lizhanqi.videosquare.activity.VideoActivity;
import com.qg.lizhanqi.videosquare.adaputer.RecyclerAdapter;
import com.qg.lizhanqi.videosquare.bean.VideoInfors;
import com.qg.lizhanqi.videosquare.uitlhelp.DividerItemDecoration;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.SimpleResponseListener;

import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private View homeView;
    private ListView videoListView;
    final String LOGININFO = "loginInfo";
    private Switch switchover;
    private RecyclerView videoRecyclerView;
    private final String url = "http://101.200.142.201:8080/VideoPlay/videolist?";
    private static final String TAG = "HomeFragment";
    private RequestQueue requestQueues;
    private SharedPreferences sharedPreferences;
    private Request<JSONObject> jsonObjectRequest;
    private int page = 1;//第几页默认是从第一页开始，
    private int pageSize = 10;//每页多少条，默认10条
    private LinkedList<VideoInfors.VideoListBean> listVideo;
    private RecyclerAdapter recyclerAdapter;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private boolean loading = false;
    private Request<String> stringRequest;
    private String userid;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        homeView = inflater.inflate(R.layout.fragment_home, container, false);
        initView(homeView);
        //获取userid
        userid = getActivity().getSharedPreferences(LOGININFO, Context.MODE_PRIVATE).getString("userid", null);
        requestString(url,userid,page,pageSize,false);
        return homeView;
    }
    private void initView(View homeView) {
        //第一步：创建Nohttp请求对列
        requestQueues = NoHttp.newRequestQueue();
        mSwipeRefreshLayout = (SwipeRefreshLayout) homeView.findViewById(R.id.swipe_Refresh_Layout);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        //开始就动画加载...
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        videoRecyclerView = (RecyclerView) homeView.findViewById(R.id.videoRecyclerView);
        //设置布局管理器：设置为ListView的样式
        videoRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //设置布局管理器：设置为GridView的样式new GridLayoutManager(getActivity(),2)传入的是上下文，每行显示几个（列数）
        //   videoRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),2));
        //设置Item增加、移除动画(默认的动画)
        videoRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
        videoRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        videoRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //可以得到当前RecyclerView中Item的总数目?
                int totalItemCount = layoutManager.getItemCount();
                //得到最后一个可见的Item的位置position
                int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                Log.i(TAG, "onScrolled:总数 " + totalItemCount + "可见：" + lastVisibleItem);
                if (totalItemCount == lastVisibleItem + 1) {
                    requestString(url,userid,++page,pageSize,false);
                }
            }
        });
    }
    public void requestString(String path, String userid, int page, int pageSize, final boolean isRefresh) {
        Log.i(TAG, "requestString: "+path+userid+page+pageSize);
        if (TextUtils.isEmpty(path)) {
            new IllegalArgumentException("路径不能为空");
            return;
        }
        if (stringRequest == null) {
            stringRequest = NoHttp.createStringRequest(path, RequestMethod.POST);
        }
        stringRequest.add("userid", userid);
        stringRequest.add("page", page);
        stringRequest.add("pageSize", pageSize);
        requestQueues.add(666, stringRequest, new SimpleResponseListener<String>() {
            @Override
            public void onSucceed(int i, Response<String> response) {
                //停止动画
                mSwipeRefreshLayout.setRefreshing(false);
                String str = response.get();
                readAndAdd(str,isRefresh);
            }
            @Override
            public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
                Toast.makeText(getActivity(), "获取数据失败", Toast.LENGTH_LONG).show();
                //停止动画
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }
    public void readAndAdd(String result,boolean isRefresh){
        List<VideoInfors.VideoListBean> mVideos = null;
        VideoInfors videos = JSON.parseObject(result, VideoInfors.class);
        String code = videos.getCode();
        if (code.equals("00000")) {
                 mVideos = videos.getVideoList();
                if (listVideo == null) {//判断添加到的list集合是否为空
                    listVideo = new LinkedList<VideoInfors.VideoListBean>();
                }
            if (mVideos.size()<1){
                Toast.makeText(getActivity(), "没有数据啦", Toast.LENGTH_SHORT).show();
            }
            for (VideoInfors.VideoListBean vs:mVideos){
                String videoid = vs.getVideoid();
                boolean ishave =false;
                for (VideoInfors.VideoListBean listv:listVideo){
                    if (listv.getVideoid().equals(videoid)){
                        ishave =true;
                    }
                }
                if (!ishave) {
                    if (isRefresh) {
                        listVideo.addFirst(vs);
                    }else {
                        listVideo.addLast(vs);
                    }
                }
        }
            //设置适配器
            if (recyclerAdapter == null) {//如果适配器为空创建并且适配
                recyclerAdapter = new RecyclerAdapter(getActivity(), listVideo);//创建适配器
                videoRecyclerView.setAdapter(recyclerAdapter);//设置适配器
                //设置适配器的监听会滴哦啊
                recyclerAdapter.setOnItemClinckListener(new RecyclerAdapter.onItemClickListener() {
                    @Override
                    public void onItemClinck(View view, int position) {
                        Intent intent = new Intent(getActivity(), VideoActivity.class);
                        VideoInfors.VideoListBean videoListBean = listVideo.get(position);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("video", videoListBean);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                    @Override
                    public void onItemLoingClinck(View view, int position) {
                        Toast.makeText(getActivity(), "长按了：" + position, Toast.LENGTH_LONG).show();
                    }
                });
            } else {
                //更新适配器
                recyclerAdapter.notifyDataSetChanged();
            }
        } else {
            Toast.makeText(getActivity(), "获取错误", Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onRefresh() {
        requestString(url,userid,1,pageSize,true);
    }
    @Override
    public void onDestroy() {
        if (jsonObjectRequest != null) {
            jsonObjectRequest.removeAll();
        }
        super.onDestroy();
    }
}
